<template>
  <!-- 新增患者 -->
  <section class="add-reserve">
    <div>
      <el-button @click="onBack">
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
    </div>
    <br />
    <div class="form-tool">
      <div>
        <el-form
          @submit.native.prevent="onSubmit"
          label-width="100px"
          label-position="top"
          ref="form"
          :model="form"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="患者姓名：" prop="name">
                <el-input v-model.trim="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="身份证号："
                prop="idCard"
                :rules="[form.certificateType==1?rulesIdCard:{}]"
              >
                <el-input v-model.trim="form.idCard" @blur="onBlurIdCard">
                  <el-select
                    v-model="form.certificateType"
                    style="width:100px;"
                    slot="prepend"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item,index) in certificateTypeArray"
                      :key="index"
                      :label="item.desc"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别：" prop="sex">
                <el-radio-group v-model.trim="form.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                  <el-radio :label="0">不详</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="出生年月：" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  :picker-options="pickerNow"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="年龄：" prop="age">
                <el-input v-model.number="form.age" type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号：" prop="mobile">
                <el-input v-model.trim="form.mobile"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信号：" prop="openId">
                <el-input v-model.trim="form.openId"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="职业：" prop="occupationId">
                <el-select v-model="form.occupationId" clearable>
                  <el-option
                    v-for="(item,index) in occupationArray"
                    :key="index"
                    :value="item.id"
                    :label="item.desc"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="民族：" prop="nationId">
                <el-select v-model="form.nationId" clearable>
                  <el-option
                    v-for="(item,index) in nationArray"
                    :key="index"
                    :value="item.id"
                    :label="item.desc"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作单位：" prop="workUnit">
                <el-input v-model.trim="form.workUnit"></el-input>
              </el-form-item>
            </el-col> 
            <el-col :span="8">
              <el-form-item label="婚姻状况：" prop="isMarried">
                <el-radio-group v-model="form.isMarried">
                  <el-radio :label="1">已婚</el-radio>
                  <el-radio :label="0">未婚</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="国籍：">
                <el-select v-model="form.nationalityId" placeholder="请选择">
                  <el-option
                    v-for="(item,index) in nationalityArray"
                    :key="index"
                    :value="item.id"
                    :label="item.desc"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="省市区：" prop="areaArray">
                <v-area :isFull="true" v-model="form.areaArray"></v-area>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="详细地址：" prop="address">
                <el-input v-model="form.address"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="患者来源：">
                <!-- <el-select v-model="form.source" placeholder="请选择">
                  <el-option v-for="(item,index) in sourceArray" :key="index" :value="item.id" :label="item.desc"></el-option>
                </el-select>-->
                <!-- <el-input placeholder="请输入推荐" v-model="form.sourceName">
                  <el-select v-model="form.source" style="width:120px;" slot="prepend">
                    <el-option
                      v-for="(it,index) in recommArray"
                      :key="index"
                      :value="it.desc"
                      :label="it.desc"
                    ></el-option>
                  </el-select>
                </el-input>-->
                <el-select
                  v-model="form.sourceType"
                  clearable
                  style="width:46%;"
                  :popper-append-to-body="false"
                   placeholder="请选择来源分类"
                  @change="getSource"
                >
                  <el-option
                    v-for="(item,index) in sourceArray"
                    :key="index"
                    :value="item.id"
                    :label="item.desc"
                  ></el-option>
                </el-select>
                <!-- <el-select style="width:46%;margin-left:2%;" v-if="form.source=='医生推荐'" filterable  :filter-method="getDoctorList" value-key="id" clearable  placeholder="请选择医生" v-model="form.tjDoctorId" >
                   <el-option v-for="it in doctorArray" :key="it.id" :value="it.id" :label="it.trueName"></el-option>
                </el-select>
                <el-select
                style="width:46%;margin-left:2%;"
                  v-else-if=" form.source == '机构推荐' || form.source == '平台宣传' || form.source == '活动宣传' "
                  value-key="id"
                  v-model="form.sourceName"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in sourceObjList"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  ></el-option>
                </el-select> -->
                  <doctorSearch
                      v-if="form.sourceType == 1"
                      ref="tjDoc"
                      :pageSize="20"
                       v-model="form.sourceCode"
                      @change="onTCDoctor"
                    ></doctorSearch>
                    <el-select
                      v-else-if="form.sourceType == 2 || form.sourceType== 3 || form.sourceType == 4"
                      value-key="id"
                      v-model="sourceObj"
                      placeholder="请选择"
                      @change="onChangeSourceObj"
                    >
                      <el-option
                        v-for="item in sourceObjList"
                        :key="item.id"
                        :label="item.name"
                        :value="item"
                      ></el-option>
                    </el-select>
                <el-input v-else style="width:46%;margin-left:2%;" placeholder="请输入来源" v-model="form.sourceName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="病人卡号：">
                <el-input v-model="form.medicalCardCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注：" prop>
                <el-input v-model="form.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="标签：">
                <el-select v-model="form.labelIds" multiple placeholder="请选择">
                  <el-option
                    v-for="(item,index) in labelArray"
                    :key="index"
                    :value="item.labelId"
                    :label="item.labelName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label prop>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="user-head">
          <img v-if="form.head" :src="form.head|imageUrl" />
          <img v-else src="@/img/unknown-avatar.png" alt />
          <div style="margin-top:7px;">
            <oneImageUpload v-show="false" v-model="form.head" ref="oneImageUpload"></oneImageUpload>
            <el-button @click="onOpenFile" style="width:100%;">上传头像</el-button>
            <div style="text-align:center;">最大可上传2M</div>
          </div>
        </div>
      </div>
    </div>
    <!-- <reserveTime v-model="dialogTime" :deptId="form.deptId" :doctorId="form.doctorId"></reserveTime> -->
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
export default {
  components: {
    oneImageUpload: () => import("@/components/oneImageUpload.vue"),
    "v-area": () => import("@/components/area.vue"),
    doctorSearch: () => import("@/pages/_com/newSearchDoctor.vue"),
    // reserveTime: () => import("./_com/reserveTime.vue")
  },
  data() {
    return {
      dialogTime: false,
      form: {
        hpId: "",
        name: "", //患者姓名
        birthday: "", //出生年月日
        head: "", //头像
        age: "",
        sex: 1,
        certificateType: 1,
        mobile: "", //电话
        email: "", //邮箱
        idCard: "", //证件编号
        isMarried: 1, //是否已婚
        nationId: "", //民族
        occupationId: "", //职业id
        nationalityId: "", //国籍
        isMarried: 0,
        workUnit: "", //工作单位
        openId: "",
        provinceId: "",
        province: "",
        city: "",
        district: "",
        cityId: "",
        districtId: "",
        address: "",
        source: "",
        sourceName: "",
        tjDoctorId:'',
        medicalCardCode: "",
        labelIds: "", //标签id
        areaArray: [],
        sourceType:'',
        sourceCode:''
      },
      sourceObj:null,
      sourceObjList:[],
      doctorArray: [], //医生
      deptArray: [], //科室
      reserveTypeArray: [], //预约类型
      sourceArray: [], //来源
      recommArray: [], //推荐来源
      nationArray: [], //民族
      occupationArray: [], //职业
      patientArray: [], //患者
      labelArray: [],
      jgEnum: [], //机构推荐
      nationalityArray: [],
      certificateTypeArray: [],
      patient_id: "0", //患者id
      //身份证验证
      rulesIdCard: { validator: validate.vPeopleNumber, trigger: "blur" },
      rules: {
        // idCard: [
        //   { required: true, message: "此项必填", trigger: "blur" },
        //   { validator: validate.vPeopleNumber, trigger: "blur" }
        // ],
        birthday: { required: true, message: "此项必选", trigger: "change" },
        age: [
          { required: true, message: "此项必填", trigger: "blur" },
          {
            validator: validate.integerNumber,
            message: "请输入正确的年龄",
            trigger: "blur"
          },
          {
            max: 500,
            type: "number",
            message: "请输入正确的年龄",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: validate.vPhone,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        name:[
           { required: true, message: "此项必填", trigger: "blur" },
           { validator: validate.verigySpacing, trigger: ["change",'blur'] }
        ]
      },
      pickerNow: {
        disabledDate(time) {
          return time.getTime() > Date.now(); //如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    };
  },
  mounted() {
    let th = this;
    th.getCommonConfigByKey("预约类型").then(res => {
      th.reserveTypeArray = res;
    });
    th.getCommonConfigByKey("推荐来源").then(res => {
      th.sourceArray = res;
    });
    th.getCommonConfigByKey("职业").then(res => {
      th.occupationArray = res;
    });
    th.getCommonConfigByKey("民族").then(res => {
      th.nationArray = res;
    });
    th.getCommonConfigByKey("国籍").then(res => {
      th.nationalityArray = res;
    });
    th.getCommonConfigByKey("推荐来源").then(res => {
      th.recommArray = res;
    });
    th.getCommonConfigByKey("证件类型").then(res => {
      th.certificateTypeArray = res;
    });
    th.getCommonConfigByKey("机构推荐").then(res => {
      th.jgEnum = res;
    });
    th.$api
      .selectLabelEmunList({
        hpId: th.adminUser.hpId,
        pageNum: 1,
        pageSize: 1000
      })
      .then(res => {
        if (res.executed) {
          th.labelArray = res.dataBody.list;
        }
      });
    // th.getCommonConfigByKey("标签").then(res => {
    //   th.labelArray = res;
    // });
    th.getDept();
    th.getDoctorList();
    th.verifyUrlAttack(th.$route.query).then(() => {
      th.patient_id = th.jieMi(th.$route.query.id);
    });
  },
  methods: {
    onSubmit() {
      let th = this;
      let j = { province: "", city: "", district: "" };
      let add = function() {
        th.$api.addPatient(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.$router.push({ path: "/page/patientList" });
          }
        });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          Object.assign(j, th.form);
          if (j.labelIds) {
            j.labelIds = j.labelIds.join(",");
          }
          j.hpId = th.adminUser.hpId;
          //读取地区
          if (th.form.areaArray.length == 3) {
            j.provinceId = th.form.areaArray[0].adcode;
            j.cityId = th.form.areaArray[1].adcode;
            j.districtId = th.form.areaArray[2].adcode;
            j.province = th.form.areaArray[0].name;
            j.city = th.form.areaArray[1].name;
            j.district = th.form.areaArray[2].name;
          }
          delete j.areaArray;
          add();
        }
      });
    },
    //
    getSource() {
      this.form.sourceName = "";
      this.form.sourceCode = "";
      this.form.tjDoctorId = null;
      this.getRecommendDetailListByType({ type: "init" });
    },
    getRecommendDetailListByType({ type }) {
      let params = {
        hpId: this.adminUser.hpId,
        type: ""
      };
      if(this.form.sourceType!=1&&this.form.sourceType!=5&&this.form.sourceType!=6){
        params.type=this.form.sourceType;
      }
      if (params.type) {
        this.$api
          .getRecommendDetailListByType({
            ...params
          })
          .then(res => {
            if (res.executed) {
              this.sourceObjList = res.dataBody;
              this.sourceObj = null;

              if (type && type === "revert") {
                this.sourceObj = this.sourceObjList.filter(
                  obj => obj.id == this.form.sourceCode
                )[0];
              } else {
                this.form.sourceName = "";
                this.form.sourceCode = "";
              }
            }
          });
      }
    },

    //推荐医生
    onTCDoctor(obj) {
      const th = this;
      th.form.tjDoctorId = obj.id;
      th.form.sourceName = obj.trueName;
      th.form.sourceCode = obj.id;
    },
    //打开选择预约时间
    // onOpenTime() {
    //   //判断是否有选择科室和医生
    //   if (this.form.deptId && this.form.doctorId) {
    //     this.dialogTime = true;
    //   }
    // },
    //读取身份证信息
    onBlurIdCard() {
      let th = this;
      const fn = () => {
        let result = th.$utils.getIdCardInfo(th.form.idCard);
        if (th.form.idCard) {
          th.form.birthday = result.birthday;
          th.form.sex = result.sex == "男" ? 1 : 2;
          th.form.age = th.$utils.getAgeToBirthday(result.birthday);
        }
      };
      validate.vPeopleNumber(null, th.form.idCard, function(err) {
        if (typeof err == "undefined") {
          fn();
        }
      });
    },
    //科室改变
    onChangeDept() {
      this.form.doctorId = "";
      this.getDoctorList();
    },
    //查询医生
    getDoctorList(name) {
      let th = this;
      let j = {
        pageNum: 1,
        pageSize: 20,
        hpId: th.adminUser.hpId,
        deptId: th.form.deptId,
        doctorName: name
      };
      th.$api.getDoctorPageList(j).then(res => {
        if (res.executed) {
          th.doctorArray = res.dataBody.list;
        }
      });
    },
    //获取科室
    getDept(name) {
      let th = this;
      let j = {
        pageNum: 1,
        pageSize: 10,
        hpId: th.adminUser.hpId,
        deptName: name
      };
      th.$api.getDepartmentPageList(j).then(res => {
        if (res.executed) {
          th.deptArray = res.dataBody.list;
        }
      });
    },
    //获取患者
    getPatient(name) {
      let th = this;
      th.patientArray = [];
    },
    //上传头像
    onOpenFile() {
      let th = this;
      th.$refs["oneImageUpload"].openFile();
    },
    onBack() {
      this.addNavMenu("", "/page/patientList");
      this.$router.push({
        path: "/page/patientList",
        query: { reset: false }
      });
    },
    //获取医生排班
    getDoctorScheduleByMonth() {
      let th = this;
      let date = new Date();
      date.setDate(date.getDate() + 1);
      let j = {
        deptId: th.form.deptId,
        doctorId: th.form.doctorId,
        hpId: th.adminUser.hpId,
        type: 1,
        startDate: th.$utils.FormatTime("yyyy-MM-dd", date.getTime()),
        days: 30
      };
      th.$api.getDoctorScheduleByMonth(j).then(res => {});
    },
    onChangeSourceObj(obj) {
      this.form.sourceName = obj.name;
      this.form.sourceCode = obj.id;
    }
  },
  watch: {
    "form.doctorId"(n, o) {
      let th = this;
      if (th.form.doctorId) {
        th.getDoctorScheduleByMonth();
      } else {
        th.form.sourceId = "";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.add-reserve {
  .user-head {
    border: 1px solid #eee;
    padding: 5px;
    img {
      width: 230px;
      display: block;
    }
  }
}
</style>

